package org.example.thread4;

/**
 * interrupt()：中断当前线程。如果该线程调用了 Object 类阻塞的 wait()，wait(long)，wait(long, int) 方法，
 * 或者是 Thread 类的 join()，join(long)，join(long, int)，sleep(long)，sleep(long, int) 方法，
 * 那么它的中断状态将被清除，并且将收到一个 InterruptedException 异常。
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/12/27 16:01
 */
public class MyThread6 extends Thread {

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            System.out.println("[" + name + "] 运行开始.");
            //在调用 sleep 休眠时，如果线程已经中断，或者休眠时被 interrupt 中断，则都会抛出 InterruptedException,同时清除中断标识，isInterrupted 返回 false
            Thread.sleep(10 * 1000);
            System.out.println("[" + name + "] 运行结束.");
        } catch (InterruptedException e) {
            System.out.println("[" + name + "] 中断异常退出，isInterrupted=" + Thread.currentThread().isInterrupted());
            e.printStackTrace();
            // 再次中断线程.
            Thread.currentThread().interrupt();
            System.out.println("[" + name + "] 中断异常退出，isInterrupted=" + Thread.currentThread().isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread6 myThread = new MyThread6();
        myThread.start();
        int sleep = 2000;
        String name = Thread.currentThread().getName();
        System.out.println("[" + name + "] " + sleep + " 毫秒后停止子线程.");
        Thread.sleep(sleep);
        myThread.interrupt();
        System.out.println("[" + name + "] " + sleep + " 运行结束.");

        // [main] 2000 毫秒后停止子线程.
        // [Thread-0] 运行开始.
        // [main] 2000 运行结束.
        // [Thread-0] 中断异常退出，isInterrupted=false
        // java.lang.InterruptedException: sleep interrupted
        // 	at java.lang.Thread.sleep(Native Method)
        // 	at org.example.thread4.MyThread6.run(MyThread6.java:20)
        // [Thread-0] 中断异常退出，isInterrupted=true

    }

}
